package com.sparrow.manage.common.service.impl;

import com.sparrow.manage.common.entity.PageInfo;
import com.sparrow.manage.common.entity.StandardEntity;
import com.sparrow.manage.common.service.BaseService;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.JpaRepository;

import java.io.Serializable;
import java.util.List;

public abstract class BaseServiceImpl<T extends StandardEntity<K>, K extends Serializable> implements BaseService<T, K> {

    protected abstract JpaRepository<T, K> getDao();

    @Override
    public T insert(T t) {
        JpaRepository<T, K> dao = getDao();
        return dao.save(t);
    }

    @Override
    public void delete(K id) {
        if(id != null){
            getDao().delete(id);
        }
    }

    @Override
    public T updateById(T t) {
        K id = t.getId();
        if(id != null){
            return this.getDao().save(t);
        }
        return null;
    }

    @Override
    public List<T> queryList(T t) {
        if(t == null){
            return this.getDao().findAll();
        }else{
            Example<T> example = Example.of(t);
            return this.getDao().findAll(example);
        }
    }

    @Override
    public PageInfo<T> queryPage(T t, int pageSize, int pageNumber, String sort, String direct) {
        Sort.Direction direction = "desc".equalsIgnoreCase(direct) ? Sort.Direction.DESC : Sort.Direction.ASC;
        Sort sorted = new Sort(direction, sort);

        Pageable pageable = new PageRequest(pageNumber, pageSize, sorted);
        Example<T> example = Example.of(t);
        Page<T> page = this.getDao().findAll(example, pageable);

        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setCount((int)page.getTotalElements());
        pageInfo.setData(page.getContent());

        return pageInfo;
    }

    @Override
    public T queryById(K id) {
        return this.getDao().findOne(id);
    }

    @Override
    public long queryTotal(){
        return this.getDao().count();
    }
}
